package book.test04;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 不同学历的岗位需求量
 */
public class MR {
    public static class MRMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        IntWritable v = new IntWritable(1);
        Text k = new Text();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //分割
            String[] data = value.toString().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
            //找到学历信息写出到Reduce
            k.set(data[14]);
            context.write(k, v);
        }
    }

    public static class MRReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        IntWritable v = new IntWritable();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            v.set(sum);
            context.write(key, v);
        }
    }

    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.set("fs.default", "hdfs://192.168.0.155:9000/");
        try {
            Job job = Job.getInstance(conf);
            job.setJarByClass(MR.class);
            job.setMapperClass(MRMapper.class);
            job.setReducerClass(MRReducer.class);

            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(IntWritable.class);

            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);

            FileInputFormat.setInputPaths(job, "/MR/Edu/input");
            Path path = new Path("/MR/Edu/put");
            if (path.getFileSystem(conf).exists(path)) {
                path.getFileSystem(conf).delete(path);
            }
            FileOutputFormat.setOutputPath(job, path);
            System.exit(job.waitForCompletion(true) ? 0 : 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
